package cn.tx.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import cn.tx.dao.EmpDao;
import cn.tx.dao.MenuDao;
import cn.tx.dao.RoleDao;
import cn.tx.model.Emp;
import cn.tx.model.Menu;
import cn.tx.model.Role;
import cn.tx.query.RoleQuery;
import cn.tx.service.RoleService;

public class RoleServiceImpl extends BaseServiceImpl<Role, RoleQuery> implements RoleService {

	private RoleDao roleDao;
	
	private EmpDao empDao;
	
	private MenuDao menuDao;
	
	

	public MenuDao getMenuDao() {
		return menuDao;
	}

	public void setMenuDao(MenuDao menuDao) {
		this.menuDao = menuDao;
	}

	public RoleDao getRoleDao() {
		return roleDao;
	}

	public EmpDao getEmpDao() {
		return empDao;
	}

	public void setEmpDao(EmpDao empDao) {
		this.empDao = empDao;
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
		this.baseDao = roleDao;
	}

	@Override
	public List<Role> selectGrantRole(RoleQuery rq,List<String> exclude) {
		//List<Role> all = roleDao.listAll();
		exclude.add("empId");
		List<Role> all = roleDao.selectObjByCondition(rq, exclude);
		Emp emp = empDao.getObjectById(rq.getEmpId());
		Set<Role> roles = emp.getRoles();
		for(Role role : all){
			if(roles.contains(role)){
				role.setChecked("yes");
			}
		}
		
		return all;
	}

	@Override
	public void updateGrantRole(Integer empId, String ids) {
		Emp emp = empDao.getObjectById(empId);
		String[] roleIds = ids.split(",");
		Set<Role> roles = new HashSet<Role>();
		for(String roleId : roleIds){
			Role role = roleDao.getObjectById(new Integer(roleId));
			roles.add(role);
		}
		emp.setRoles(roles);
	}

	@Override
	public void updateGrantPerm(Integer roleId, String menuIds) {
		Role role = roleDao.getObjectById(roleId);
		Set<Menu> ms = new HashSet<Menu>();
		if(StringUtils.isNotBlank(menuIds)){
			String[] mIds = menuIds.split(",");
			for(String menuId : mIds){
				Menu menu = menuDao.getObjectById(new Integer(menuId));
				ms.add(menu);
			}
		}
		role.setMenus(ms);
	}

	
	
	

}
